package cn.wangzg.fragmentdemo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;

public class NewsBrowseActivity extends AppCompatActivity implements TitleFragment.OnItemClick{
    boolean dualPane; // 是否在一屏上同时显示列表和详细内容
    int curCheckPosition = 0; // 当前选择的索引位置
    TitleFragment titleFragment;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_browse);

        // 获取布局文件中添加的fragment
        View fragTitle = findViewById(R.id.frag_title);
        // 判断是否在一屏上同时显示列表和详细内容
        dualPane = fragTitle != null;
        if (savedInstanceState != null) {
            curCheckPosition = savedInstanceState.getInt("curChoice", 0); // 更新当前选择的索引位置
        }
        if (dualPane) { // 如果在一屏上同时显示列表和详细内容
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fl_content,DetailFragment.newInstance(
                            Data.TITLES[curCheckPosition],Data.DETAIL[curCheckPosition]))
                    .commit();
        }else {
            titleFragment=new TitleFragment();
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fl_content,titleFragment)
                    .commit();
        }
    }

    @Override
    public void onAttachFragment(@NonNull Fragment fragment) {
        if (fragment instanceof TitleFragment) {
            TitleFragment titleFragment = (TitleFragment) fragment;
            titleFragment.setOnItemClick(this);
        }
    }

    @Override
    public void onTitleSelected(int position) {
        curCheckPosition=position;
        if (dualPane) { // 如果在一屏上同时显示列表和详细内容
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fl_content,DetailFragment.newInstance(
                            Data.TITLES[position],Data.DETAIL[position]))
                    .commit();
        }else {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fl_content,DetailFragment.newInstance(
                            Data.TITLES[position],Data.DETAIL[position]))
                    .addToBackStack(null)
                    .commit();
        }
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("curChoice",curCheckPosition);
    }
}
